package problems.daily.y2022m7;


import java.util.HashMap;
import java.util.Map;

/**
 * @author habitplus
 * @since 2022/7/29 10:51
 */
public class D20220727_593 {
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        int[][] points = new int[][]{p1, p2, p3, p4};
        int n = points.length;
        Map<Integer, Integer> edge = new HashMap<>();
        // 存边的集合
        int t;
        for (int i = 0; i != n-1; i++) {
            for (int j = i + 1; j < n; j++) {
                int d = distance(points[i], points[j]);
                t = 1;
                if (edge.containsKey(d))
                    t = edge.get(d) + 1;
                edge.put(d, t);
            }
        }

        // 如果不是两种长度的边，一定不能组成正方形
        if (edge.size() != 2) return false;

        // 求长边和短边
        int small = -1, big = 0;
        for (int e : edge.keySet()) {
            if (big < e) {
                small = big;
                big = e;
            } else if (small < e) {
                small = e;
            }
        }
        // 长边 = 短边 * 2 （平方）
        return small * 2 == big && 2 * edge.get(big) ==  edge.get(small);

    }

    // 求两点距离的平方
    private int distance(int[] p1, int[] p2) {
        int dx = p1[0] - p2[0];
        int dy = p1[1] - p2[1];
        return dx * dx + dy * dy;
    }

    public static void main(String[] args) {
        int [][] t = {
                {1134,-2539},
                {492,-1255},
                {-792,-1897},
                {-150,-3181}
        };
        System.out.println(new D20220727_593().validSquare(t[0], t[1], t[2], t[3]));
    }
}
